import { DefineComponent } from 'vue'
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { getFloderFiles } from '@/utils/utils'

//读取views下的view文件，自动添加路由(实际项目不建议这样搞，老老实实写路由配置，我写demo偷偷懒可以 😁)
const getPages: () => Array<RouteRecordRaw> = function () {
  const files = require.context('../views', true, /\.vue$/)
  const createRoots: Array<RouteRecordRaw> = []
  getFloderFiles(files).forEach(item => {
    if (item.resolveFilePath.split('/').includes('components')) return
    const name: string = item.filename
    const path: string = name === 'index' ? '/' : `/${name.toLocaleLowerCase()}`
    const component: DefineComponent = name === 'index' ? require(`@/views/${item.resolveFilePath}`).default : () => import(`@/views/${item.resolveFilePath}`)
    createRoots.push({ path, name, component })
  })
  return createRoots
}

const routes: Array<RouteRecordRaw> = []

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: [...getPages(), ...routes]
})

export default router
